package cn.message.service.impl;

import cn.itcast.mapper.orderMapper;
import cn.itcast.mapper.orderItemMapper;
import cn.itcast.pojo.*;
import cn.itcast.util.CommonUtil;
import cn.message.service.MessageOrderService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.itcast.util.HttpClientUtil.doPost;

/**
 * @author 辉
 * @title: MessageOrderServiceImpl
 * @projectName wx_shop
 * @description: TODO
 * @date 2019/6/1821:23
 */
@Service
@Slf4j
public class MessageOrderServiceImpl implements MessageOrderService {

    @Resource
    orderMapper orderMapper;

    @Resource
    orderItemMapper orderItemMapper;

    @Resource
    cn.itcast.mapper.horsemanMapper horsemanMapper;

    @Resource
    cn.itcast.mapper.gzhMapper gzhMapper;

    @Override
    public List<order> findAllProduct(Map<String,String> map) {
//        orderExample orderExample = new orderExample();
//        cn.itcast.pojo.orderExample.Criteria criteria = orderExample.createCriteria();
//        //获取前台传递的数据
//        Integer page = Integer.parseInt(map.get("page"));
//        Integer limit = Integer.parseInt(map.get("limit"));
//        String orderState = map.get("orderState");
//        String userName = map.get("userName");
//        String horsemanName = map.get("horsemanName");
//        String adminPhone = map.get("adminPhone");
//        String orderNumber = map.get("orderNumber");
//        String role = map.get("role");
//        String[] dateRanges = {};
//        Date startDate = null;
//        Date endDate = null;
//        if (!map.get("dateRange").isEmpty()) {
//            dateRanges = map.get("dateRange").split(",");
//            try {
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//                startDate = sdf.parse(dateRanges[0]);
//                endDate = sdf.parse(dateRanges[1]);
//
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//        }
//        //分页
//        PageHelper.startPage(page, limit);
//
//        log.debug(adminPhone);
//        HashMap<String, Object> parameterMap = new HashMap<String,Object>();
//        parameterMap.put("orderState",orderState);
//        parameterMap.put("userName",userName);
//        parameterMap.put("horsemanName",horsemanName);
//        parameterMap.put("startDate",startDate);
//        parameterMap.put("endDate",endDate);
//        parameterMap.put("adminPhone",adminPhone);
//        parameterMap.put("role",role);
//        parameterMap.put("orderNumber",orderNumber);
//        List<order> orders =  orderMapper.getAllOrder(parameterMap);
//        return orders;

        //获取前台传递的数据
        Integer page = Integer.parseInt(map.get("page"));
        Integer limit = Integer.parseInt(map.get("limit"));
        String orderState = map.get("orderState");
        String userName = map.get("userName");
        String horsemanName = map.get("horsemanName");
        String adminPhone = map.get("adminPhone");
        String orderNumber = map.get("orderNumber");
        String role = map.get("role");
        String[] dateRanges = {};
        Date startDate = null;
        Date endDate = null;
        if (!map.get("dateRange").isEmpty()) {
            dateRanges = map.get("dateRange").split(",");
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                startDate = sdf.parse(dateRanges[0]);
                endDate = sdf.parse(dateRanges[1]);

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        //添加查询条件
        orderExample orderExample = new orderExample();
        cn.itcast.pojo.orderExample.Criteria criteria = orderExample.createCriteria();
        if(!orderState.isEmpty()){
            criteria.andOrderStateEqualTo(orderState);
        }
        if(!userName.isEmpty()){
            criteria.andUserNameLike("%"+userName+"%");
        }
        if(!horsemanName.isEmpty()){
            criteria.andHorsemanNameLike("%"+horsemanName+"%");
        }
        if(!map.get("dateRange").isEmpty()){
            criteria.andPayTimeBetween(startDate,endDate);
        }
        if(!orderNumber.isEmpty()){
            criteria.andOrderNumberLike("%"+orderNumber+"%");
        }

        //按某个属性排序，默认按支付时间逆序排序
        if(map.get("prop") != null && map.get("prop") != "" && map.get("order") != null && map.get("order") != ""){
            String order = "desc";
            if(map.get("order").equals("ascending")){
                order = "asc";
            }
            if(map.get("prop").equals("payTime")){
                orderExample.setOrderByClause("pay_time "+order);
            }
        }else {
            orderExample.setOrderByClause("pay_time desc");
        }

        //判断登录的用户是否是商家管理员，如果是，则查询该商家旗下的骑手的订单，如果不是，则查询所有的订单
        if(!map.get("adminPhone").isEmpty() && role.contains("merchantAdmin")){
            horsemanExample horsemanExample = new horsemanExample();
            cn.itcast.pojo.horsemanExample.Criteria horsemanCriteria = horsemanExample.createCriteria();
            horsemanCriteria.andHorsemanReferrerEqualTo(map.get("adminPhone"));
            List<horseman> horsemanList = horsemanMapper.selectByExample(horsemanExample);
            ArrayList<String> horsemanNameList = new ArrayList<>();
            for (horseman horseman : horsemanList) {
                horsemanNameList.add(horseman.getHorsemanName());
            }
            criteria.andHorsemanNameIn(horsemanNameList);
        }
        //分页
        PageHelper.startPage(page, limit);
        List<order> orderList = orderMapper.selectByExample(orderExample);
        return orderList;

    }

    /**
     *功能：获取订单明细
     * @author 欧阳辉
     * @date 2019/6/18
      * @param orderId
     * @return java.util.List<cn.itcast.pojo.order_item>
     */
    @Override
    public List<orderItem> findOrderItem(Integer orderId) {
        if(StringUtils.isNotBlank(ObjectUtils.toString(orderId))){
            orderItemExample order_itemExample = new orderItemExample();
            cn.itcast.pojo.orderItemExample.Criteria criteria = order_itemExample.createCriteria();
            criteria.andOrderIdEqualTo(orderId);
            return orderItemMapper.selectByExample(order_itemExample);
        }else {
            log.debug("订单Id为空");
        }
        return null;
    }



    @Override
    public List<horseman> getAllHorseman(Integer pageNum, Integer pageSize, String select, String value) {

        //分页
        PageHelper.startPage(pageNum, pageSize);
        horsemanExample hEx = new horsemanExample();
        String horsemanStatus = "1";
        cn.itcast.pojo.horsemanExample.Criteria criteria = hEx.createCriteria();
        if(select.equals("horsemanName")){
            criteria.andHorsemanNameLike("%"+value+"%");
        }else  if(select.equals("horsemanNumber")){
            criteria.andHorsemanNumberLike("%"+value+"%");
        }else  if(select.equals("horsemanPhone")){
            criteria.andHorsemanPhoneLike("%"+value+"%");
        }else  if(select.equals("horsemanIdNumber")){
            criteria.andHorsemanIdNumberLike("%"+value+"%");
        }
        criteria.andHorsemanIsopenEqualTo(horsemanStatus);


        return horsemanMapper.selectByExample(hEx);
    }

    @Override
    public boolean sendOrder(Integer orderId, String openId, String name) {
        order order = new order();
        order.setOrderState("待接单");
        order.setHorsemanAccount(openId);
        order.setHorsemanName(name);
        order.setId(orderId);
        int i = orderMapper.updateByPrimaryKeySelective(order);

        order dataOrder = orderMapper.selectByPrimaryKey(orderId);
        if(i==1){
            log.debug("开始推送");
            //推送消息给骑手，提醒接单
            String token = gzhMapper.selectByPrimaryKey(2).getAccessToken();
            Template template=new Template();
            template.setTemplate_id("OjiwqySOKJYbrlVYMxX8b4GAUwHdhQISHEf3FH6dgH0");
            template.setTouser(openId);
            template.setPage("pages/order/main");
            List<TemplateParam> paras=new ArrayList<TemplateParam>();
            paras.add(new TemplateParam("time1",dataOrder.getOrderVisitTime().substring(0,5)));
            paras.add(new TemplateParam("thing3",dataOrder.getPayProductType().substring(0,Math.min(19,dataOrder.getPayProductType().length()))));
            paras.add(new TemplateParam("thing4",dataOrder.getPayForecastWeight()));
            paras.add(new TemplateParam("thing5",dataOrder.getUserArea().substring(dataOrder.getUserArea().indexOf("市")+1,Math.min(dataOrder.getUserArea().indexOf("市")+20,dataOrder.getUserArea().length()))));
            paras.add(new TemplateParam("phone_number10",dataOrder.getUserPhone()));
            template.setTemplateParamList(paras);
            String requestUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
            requestUrl=requestUrl.replace("ACCESS_TOKEN", token);

            System.out.println(template.toJSON());
            net.sf.json.JSONObject jsonResult= CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());
            if(jsonResult!=null){
                System.out.println(jsonResult);
                int errorCode=jsonResult.getInt("errcode");
                String errorMessage=jsonResult.getString("errmsg");
                if(errorCode==0){
                   log.debug("提醒骑手接单Send Success");
                }else{
                    log.debug("订阅消息发送失败:"+errorCode+","+errorMessage);
                }
            }

//            String createUlr = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+token;
//            Map<String,String> param = new HashMap<>();
//            param.put("touser",openId);
//            param.put("template_id","OjiwqySOKJYbrlVYMxX8b3gbnlg3r4l13qlH87nGrJY");
//            param.put("page","pages/order/main");
//            Map<String,Object> data = new HashMap<>();
//            data.put("time1",new HashMap<String,String>().put("value",dataOrder.getOrderVisitTime()));
//            data.put("thing3",new HashMap<String,String>().put("value",dataOrder.getPayProductType()));
//            data.put("thing4",new HashMap<String,String>().put("value",dataOrder.getPayForecastWeight()));
//            data.put("thing5",new HashMap<String,String>().put("value",dataOrder.getUserArea()));
//            data.put("phone_number10",new HashMap<String,String>().put("value",dataOrder.getUserPhone()));
//            param.put("data",data.toString());
//            String result = doPost(createUlr, param);
//            log.debug("推送消息:"+result);

            //com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
            //log.debug(object.getString("open_appid"));

            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<order> exportOrderExcel(Map<String,String> map) {
        //获取前台传递的数据
        String orderState = map.get("orderState");
        String userName = map.get("userName");
        String horsemanName = map.get("horsemanName");
        String adminPhone = map.get("adminPhone");
        String role = map.get("role");
        String orderNumber = map.get("orderNumber");

        String[] dateRanges = {};
        Date startDate = null;
        Date endDate = null;
        if (!map.get("dateRange").isEmpty()) {
            dateRanges = map.get("dateRange").split(",");
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                startDate = sdf.parse(dateRanges[0]);
                endDate = sdf.parse(dateRanges[1]);

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        HashMap<String, Object> parameterMap = new HashMap<>();
        parameterMap.put("orderState",orderState);
        parameterMap.put("userName",userName);
        parameterMap.put("horsemanName",horsemanName);
        parameterMap.put("adminPhone",adminPhone);
        parameterMap.put("startDate",startDate);
        parameterMap.put("endDate",endDate);
        parameterMap.put("role",role);
        parameterMap.put("orderNumber",orderNumber);
        List<order> orderList = orderMapper.getAllOrder(parameterMap);
        for (order order : orderList) {
            List<orderItem> orderItems = orderItemMapper.getOrderItemByOrderId(order.getId());
            order.setOrderItems(orderItems);
        }
        return orderList;
    }
}
